package com.example.xianji.activity;

import java.util.ArrayList;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.NewsAdapter;
import com.example.xianji.BGARefresh.BGARefreshLayout;
import com.example.xianji.BGARefresh.BGARefreshLayout.BGARefreshLayoutDelegate;
import com.example.xianji.bean.news;
import com.example.xianji.utils.DataCleanManager;

import com.example.xianji.eventbus.DianJi_EventBus;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * 新闻列表页面
 *
 * @author me
 */
public class Main_newsActivity extends Activity implements
        BGARefreshLayoutDelegate, OnClickListener {
    /**
     * 新闻搜索关键词
     */
    public static String newsSearchContant = "";
    /**
     * 加载数据时获取到的高亮词数组
     */
    public static JSONArray high_light_word = new JSONArray();
    /************************* 新闻资讯列表页面 *************************************/
    private ImageView news_image_load, news_search;
    private RelativeLayout jingcai_news_back;
    private ArrayList<news> news_list = new ArrayList<news>();
    private BGARefreshLayout news_RefreshLayout;
    private ListView news_myListview;
    private NewsAdapter mNews_Adapter;// 新闻资讯列表适配器
    private int page = 1;
    private AnimationDrawable news_animation;
    private Button button_xianji_home, button_xianji_skill,
            button_xianji_luntan, button_xianji_zixun, button_xianji_xuqiu,
            button_xianji_fuwu, button_xianji_zhanhui,
            button_xianji_choose_product, button_xianji_qiye;
    private int index = -1;
    private int current_index = 3;
    private ArrayList<Button> button_list = new ArrayList<Button>();
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                news_myListview.setAdapter(mNews_Adapter);
                news_RefreshLayout.endRefreshing();
                DataCleanManager.clearAllCache(getApplicationContext());
                news_animation.stop();
                news_image_load.setVisibility(View.GONE);
            }
            if (msg.what == 2) {
                mNews_Adapter.notifyDataSetChanged();
                news_RefreshLayout.endLoadingMore();
                DataCleanManager.clearAllCache(getApplicationContext());
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main_news);
        init();
        newsSearchContant = "";
        index = current_index;

        jingcai_news_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //离开新闻列表页面删除 存在本地的图片和指定文件夹
                // SaveSdk.deleteFile();
                Main_newsActivity.this.finish();
            }
        });
        XJApplication.cachThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                get_news();
            }
        });
        processLogic(savedInstanceState);
    }

    private void init() {
        jingcai_news_back = (RelativeLayout) findViewById(R.id.jingcai_news_relative_back);
        news_RefreshLayout = (BGARefreshLayout) findViewById(R.id.news_RefreshLayout);
        news_myListview = (ListView) findViewById(R.id.news_myListview);
        mNews_Adapter = new NewsAdapter(Main_newsActivity.this, news_list);
        news_image_load = (ImageView) findViewById(R.id.news_image_load);
        news_search = (ImageView) findViewById(R.id.news_search);
        news_animation = (AnimationDrawable) news_image_load.getDrawable();
        news_animation.start();
        button_xianji_home = (Button) findViewById(R.id.button_xianji_home);
        button_xianji_skill = (Button) findViewById(R.id.button_xianji_skill);
        button_xianji_luntan = (Button) findViewById(R.id.button_xianji_luntan);
        button_xianji_zixun = (Button) findViewById(R.id.button_xianji_zixun);
        button_xianji_xuqiu = (Button) findViewById(R.id.button_xianji_xuqiu);
        button_xianji_fuwu = (Button) findViewById(R.id.button_xianji_fuwu);
        button_xianji_zhanhui = (Button) findViewById(R.id.button_xianji_zhanhui);
        button_xianji_choose_product = (Button) findViewById(R.id.button_xianji_choose_product);
        button_xianji_qiye = (Button) findViewById(R.id.button_xianji_qiye);

        button_list.add(button_xianji_home);
        button_list.add(button_xianji_skill);
        button_list.add(button_xianji_luntan);
        button_list.add(button_xianji_zixun);
        button_list.add(button_xianji_xuqiu);
        button_list.add(button_xianji_fuwu);
        button_list.add(button_xianji_zhanhui);
        button_list.add(button_xianji_choose_product);
        button_list.add(button_xianji_qiye);

        button_list.get(current_index).setTextColor(getResources().getColor(R.color.blue22));

        button_xianji_home.setOnClickListener(this);
        button_xianji_skill.setOnClickListener(this);
        button_xianji_luntan.setOnClickListener(this);
        button_xianji_zixun.setOnClickListener(this);
        button_xianji_xuqiu.setOnClickListener(this);
        button_xianji_fuwu.setOnClickListener(this);
        button_xianji_zhanhui.setOnClickListener(this);
        button_xianji_choose_product.setOnClickListener(this);
        button_xianji_qiye.setOnClickListener(this);
        news_RefreshLayout.setDelegate(this);// 下拉刷新上拉加载监听
        news_search.setOnClickListener(this);
    }

    protected void processLogic(Bundle savedInstanceState) {
        news_RefreshLayout.setRefreshViewHolder(new com.example.xianji.BGARefresh.BGANormalRefreshViewHolder(
                this, true));
    }

    public void get_news() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("page", 1 + "");
        parms.addBodyParameter("k", newsSearchContant);
        httpUtils.send(HttpMethod.POST, Contant.news, parms,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        news_RefreshLayout.endRefreshing();
                        news_animation.stop();
                        news_image_load.setVisibility(View.GONE);
                        Toast.makeText(Main_newsActivity.this, "加载失败", Toast.LENGTH_SHORT)
                                .show();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject object = new JSONObject(arg0.result);
                            if (object.getInt("status") == 1) {
                                news_list.clear();
                                JSONArray array = object.getJSONArray("data");
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject obj = array.getJSONObject(i);
                                    news mnews = new news();
                                    mnews.setDescription(obj
                                            .getString("description"));
                                    mnews.setId(obj.getString("id"));
                                    mnews.setPath(obj.getJSONObject("uploads")
                                            .getString("path"));
                                    mnews.setName(obj.getJSONObject("uploads")
                                            .getString("name"));
                                    mnews.setNews_title(obj
                                            .getString("news_title"));
                                    JSONArray hight_array = new JSONArray();
                                    mnews.setHight_light_pos(hight_array);
                                    mnews.setDetail_hig_light(hight_array);
                                    news_list.add(mnews);
                                }
                                high_light_word = object.getJSONArray("high_light_word");
                                handler.sendEmptyMessage(1);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void get_news_more() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("page", page + "");
        parms.addBodyParameter("k", newsSearchContant);
        httpUtils.send(HttpMethod.POST, Contant.news, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        news_RefreshLayout.endLoadingMore();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject object = new JSONObject(arg0.result);
                            if (object.getInt("status") == 1) {
                                JSONArray array = object.getJSONArray("data");
                                if (array.length() > 0) {
                                    for (int i = 0; i < array.length(); i++) {
                                        JSONObject obj = array.getJSONObject(i);
                                        news mnews = new news();
                                        mnews.setDescription(obj
                                                .getString("description"));
                                        mnews.setId(obj.getString("id"));
                                        mnews.setPath(obj.getJSONObject(
                                                "uploads").getString("path"));
                                        mnews.setName(obj.getJSONObject(
                                                "uploads").getString("name"));
                                        mnews.setNews_title(obj
                                                .getString("news_title"));
                                        JSONArray hight_array = new JSONArray();
                                        mnews.setHight_light_pos(hight_array);
                                        mnews.setDetail_hig_light(hight_array);
                                        news_list.add(mnews);
                                    }
                                } else {
                                    Toast.makeText(Main_newsActivity.this,
                                            "加载完毕没有更多数据", Toast.LENGTH_SHORT).show();
                                }
                                handler.sendEmptyMessage(2);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                page = 1;
                get_news();
            }
        });
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(
            BGARefreshLayout refreshLayout) {
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                page++;
                get_news_more();
            }
        });
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        NewsAdapter.AnimateFirstDisplayListener.displayedImages.clear();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_xianji_home) {
            current_index = 0;
            Main_newsActivity.this.finish();
        } else if (v.getId() == R.id.button_xianji_skill) {
            current_index = 1;
            startActivity(new Intent(Main_newsActivity.this,
                    Main_Skill_Activity.class));
        } else if (v.getId() == R.id.news_search) {
            //新闻搜索
            Intent intent = new Intent(Main_newsActivity.this, Main_SearchActivity.class);
            intent.putExtra("search", 9);

            startActivity(intent);

        } else if (v.getId() == R.id.button_xianji_luntan) {
            current_index = 2;
            /**
             * 跳转到浏览器
             */
            try {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                // intent.putExtra("fa", 1);
                Uri content_url = Uri.parse("http://m.bbs.xianjichina.com/");

                // 如果手机本身没有默认浏览器，就跳转到系统自带的浏览器，避免三星机型崩溃问题
                intent.setClassName("com.android.browser",
                        "com.android.browser.BrowserActivity");

                intent.setData(content_url);
                startActivity(intent);
            } catch (Exception e) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                // intent.putExtra("fa", 1);
                Uri content_url = Uri.parse("http://m.bbs.xianjichina.com/");
                intent.setData(content_url);
                startActivity(intent);
            }
        } else if (v.getId() == R.id.button_xianji_zixun) {
            current_index = 3;

        } else if (v.getId() == R.id.button_xianji_xuqiu) {
            current_index = 4;
            EventBus.getDefault().postSticky(new DianJi_EventBus(false, true));
            Main_newsActivity.this.finish();
        } else if (v.getId() == R.id.button_xianji_fuwu) {
            current_index = 5;
            startActivity(new Intent(Main_newsActivity.this,
                    Main_FuWuActivity.class));
        } else if (v.getId() == R.id.button_xianji_zhanhui) {
            current_index = 6;
            startActivity(new Intent(Main_newsActivity.this,
                    Main_ZhanHui_DaTingActivity.class));
        } else if (v.getId() == R.id.button_xianji_choose_product) {
            /****************** 从这里跳转到选型大厅页面，返回键显示 *******************/
            Contant.choose_dating_back = 2;
            current_index = 7;
            startActivity(new Intent(Main_newsActivity.this,
                    Main_Choose_DaTing_LieBiaoActivity.class));
        } else if (v.getId() == R.id.button_xianji_qiye) {
            current_index = 8;
            startActivity(new Intent(Main_newsActivity.this,
                    Main_Find_QiYeActivity.class));
        }

        button_list.get(current_index).setTextColor(
                getResources().getColor(R.color.blue22));
        if (index == -1) {

        } else {
            button_list.get(index).setTextColor(
                    getResources().getColor(R.color.black3F));
        }
        index = current_index;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Main_SearchActivity.news_search_id == 1) {

            XJApplication.cachThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    get_news();
                }
            });
            Main_SearchActivity.news_search_id = 0;
        }
    }
}
